# -*- coding: utf-8 -*-

from adrianremembersme import AdrianRemembersMe
from decorators        import login_required

import logging

class MemberMiddleware(object):
    """
        This middleware provides 'request.member' helper for every view.
    """
    def process_view(self, request, view_func, view_args, view_kwargs ):
        cookie = request.COOKIES.get('user','')
        member = AdrianRemembersMe().is_logged(cookie_val=cookie)

        request.member_cookie = cookie
        request.member = member
        
        logging.info("Member: %s", member and member.name)


class RequireLoginMiddleware(object):
    """
        This middleware enforces automatic login for every view.
        You add exceptions using the decorator @login_not_required decorator
    """
    def process_view(self, request, view_func, view_args, view_kwargs):
        try:
            # page is public, please go on
            public_page = getattr(view_func, 'public_page')
            if public_page:
                return None

        except AttributeError:
            return login_required(view_func)(request, *view_args, **view_kwargs)
